package meta.common.util;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {

    public static boolean checkFileExist(File file) {
        return file.exists() && file.isFile();
    }

    public static boolean checkFileExist(String filePath) {
        File file = new File(filePath);
        return checkFileExist(file);
    }

    public static boolean checkDirExist(File dir) {
        return dir.exists() && dir.isDirectory();
    }

    public static boolean checkDirExist(String dirPath) {
        File dir = new File(dirPath);
        return checkDirExist(dir);
    }

    public static List<String> listSubdir(String root, String path, boolean prefix) {
        if (!checkDirExist(root + path)) {
            return null;
        }
        File dir = new File(root + path);
        File[] files = dir.listFiles();
        if (files == null || files.length == 0) {
            return null;
        }
        List<String> result = new ArrayList<String>();
        for (File file : files) {
            if (checkDirExist(file)) {
                if (prefix) {
                    result.add(path + file.getName());
                } else {
                    result.add(file.getName());
                }
            }
        }
        return result;
    }

    public static List<String> listSubfile(String root, String path, boolean prefix) {
        if (!checkDirExist(root + path)) {
            return null;
        }
        File dir = new File(root + path);
        File[] files = dir.listFiles();
        if (files == null || files.length == 0) {
            return null;
        }
        List<String> result = new ArrayList<String>();
        for (File file : files) {
            if (checkFileExist(file)) {
                if (prefix) {
                    result.add(path + file.getName());
                } else {
                    result.add(file.getName());
                }
            }
            if (checkDirExist(file)) {
                File[] subfiles = file.listFiles();
                if (subfiles == null || subfiles.length == 0) {
                    continue;
                }
                for (File subfile : subfiles) {
                    if (checkFileExist(subfile)) {
                        if (prefix) {
                            result.add(path + file.getName() + "/" + subfile.getName());
                        } else {
                            result.add(file.getName() + "/" + subfile.getName());
                        }
                    }
                }
            }
        }
        return result;
    }
}
